<script setup lang="tsx">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import UpLoad from '@/components/upLoad/index.vue';
import IageViewer from '@/components/imageViewer/index.vue';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import { Space, Link, MessagePlugin } from 'tdesign-vue-next';
import { AddIcon } from 'tdesign-icons-vue-next';
import { getPrizeList, add, edit, getInfo, Delete } from '@/api/lucky/prizeAdmin';
const { t } = useI18n();

const data = ref([]);

const columns = [
  {
    title: '奖品ID',
    colKey: 'id',
  },
  {
    title: '奖品名称',
    colKey: 'prizeName',
  },
  {
    title: '奖金',
    colKey: 'money',
  },
  {
    title: '奖品图片',
    colKey: 'image',
  },
  {
    title: '中奖概率(%)',
    colKey: 'odds',
  },
  {
    title: '奖品总数',
    colKey: 'number',
  },
  {
    title: '剩余奖品',
    colKey: 'remainNum',
  },
  {
    title: '操作',
    colKey: 'op',
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        新增
      </t-button>
    </OperatingBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      rowKey="id"
      onUnGetList={unGetList}
    >
      {{
        money: (slotProps: any) => (
          <div>
            {new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
              slotProps.row.money,
            )}
          </div>
        ),
        image: (slotProps: any) => (
          <div>
            {slotProps.row.image && <IageViewer img={import.meta.env.VITE_PROXY_API_URL + slotProps.row.image} />}
          </div>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="primary" onClick={() => unEdit(slotProps)}>
              修改
            </Link>
            <Link theme="danger" onClick={() => deleteClickOp(slotProps, false)}>
              {t('pages.detailCard.detail.form.delete')}
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

const unGetList = async () => {
  try {
    const res = await getPrizeList({
      pageNum: pagination.value.defaultCurrent,
      pageSize: pagination.value.defaultPageSize,
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};

unGetList();

/** 添加对话框 */
const formObj = new formGroup();
const unAdd = async () => {
  try {
    formObj.show('添加奖品', {}, '添加奖品');
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '添加奖品',
  '添加奖品',
  {},
  async (body) => {
    await add(body.data);
    unGetList();
  },
  {
    prizeName: [{ required: true, message: '奖品名称不能为空', trigger: 'blur' }],
    money: [{ required: true, message: '奖金不能为空', trigger: 'blur' }],
    odds: [{ required: true, message: '中奖率不能为空', trigger: 'blur' }],
    number: [{ required: true, message: '奖品总数不能为空', trigger: 'blur' }],
  },
);

// 详情
const unEdit = async (slotProps: any) => {
  try {
    let res = await getInfo(slotProps.row.id);
    formObj.show(
      '编辑奖品',
      {
        ...res.data,
      },
      '编辑奖品',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '编辑奖品',
  '编辑奖品',
  {},
  async (body) => {
    await edit(body.data);
    unGetList();
  },
  {
    prizeName: [{ required: true, message: '奖品名称不能为空', trigger: 'blur' }],
    money: [{ required: true, message: '奖金不能为空', trigger: 'blur' }],
    odds: [{ required: true, message: '中奖率不能为空', trigger: 'blur' }],
    number: [{ required: true, message: '奖品总数不能为空', trigger: 'blur' }],
  },
);

// 删除
const confirmVisible = ref(false);
const deleteId = ref([]);
const onConfirmDelete = () => {
  let ids = deleteId.value.join(',');
  Delete(ids).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    unGetList();
  });
};

const deleteClickOp = (value: any, isSingle: boolean) => {
  if (isSingle && !value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  confirmVisible.value = true;
  deleteId.value = isSingle ? value : [value.row.id];
};
</script>

<template>
  <div>
    <render />
    <FormDialogGroup :form-obj="formObj">
      <template #default="{ formData, item }">
        <!-- 添加奖品对话框 -->
        <template v-if="item == '添加奖品' || item == '编辑奖品'">
          <t-form-item label="奖品名称" name="prizeName" help="如：999元">
            <t-input v-model="formData.prizeName" placeholder="请输入奖品名称" />
          </t-form-item>
          <t-form-item label="奖金" name="money" help="如：999，大于0直接返到用户余额">
            <div class="capital">
              <t-input-number v-model="formData.money" placeholder="请输入奖金" />
            </div>
          </t-form-item>
          <t-form-item label="中奖率(%)" name="odds">
            <div class="capital">
              <t-input-number v-model="formData.odds" placeholder="请输入中奖率" />
            </div>
          </t-form-item>
          <t-form-item label="n次必中" name="winTimes" help="每n次抽奖必中此奖品">
            <div class="capital">
              <t-input-number v-model="formData.winTimes" placeholder="请输入抽奖次数" />
            </div>
          </t-form-item>
          <t-form-item label="奖品总数" name="number">
            <div class="capital">
              <t-input-number v-model="formData.number" placeholder="请输入奖品总数" />
            </div>
          </t-form-item>
          <t-form-item label="奖品图片" name="image">
            <UpLoad v-model:image="formData.image" :key="formData.image"></UpLoad>
          </t-form-item>
        </template>
      </template>
    </FormDialogGroup>
    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选项目？"
      body="删除后，数据将被清空，且无法恢复"
      @confirm="onConfirmDelete"
    />
  </div>
</template>

<style lang="less" scoped>
.capital .t-input-number.t-input-number--row {
  width: 314px;
  display: flex;
  align-items: center;
  padding: 0 38px;

  .t-button.t-button--variant-outline.t-button--theme-default.t-button--shape-square.t-button--icon-only {
    width: 38px;
    height: 38px;
  }
}
</style>
<style>
.capital .t-input-number .t-input.t-align-center {
  width: 230px !important;
}
</style>
